const db = require('../db/index')

//添加收货地址
exports.upaddress = (req, res) => {
    const sql = 'INSERT INTO hb_address set ?'
    const addressinfo = { user_account: req.user.user_account, ...req.body }
    db.query(sql, addressinfo, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('收货地址添加失败')
        res.cc('添加成功！', 200)
    })
}

//获取当前用户的收货地址
exports.getAddressInfo = (req, res) => {
    const sql = 'select * from hb_address where user_account = ?'
    db.query(sql, req.user.user_account, (err, results) => {
        if (err) return res.cc(err)
        // if (results.length === 0) return res.cc('无地址！')
        res.send({
            status: 200,
            data: results
        })
    })
}

//修改收货地址
exports.updateAddress = (req, res) => {
    const sql = 'UPDATE hb_address SET ? WHERE address_id = ?';
    const { address_id, ...addressInfo } = req.body;
    db.query(sql, [addressInfo, address_id], (err, results) => {
        if (err) return res.cc(err);
        if (results.affectedRows !== 1) return res.cc('修改失败！');
        res.cc('修改成功！', 200);
    });
};

//删除收货地址
exports.deleteaddress = (req, res) => {
    const addressIds = Array.isArray(req.body.address_id) ? req.body.address_id : [req.body.address_id];
    const sql = 'DELETE FROM hb_address WHERE address_id IN (?)';
    db.query(sql, [addressIds], (err, results) => {
        console.log(addressIds);
        if (err) return res.cc(err);
        if (results.affectedRows === 0) return res.cc('删除失败！');
        return res.cc('删除成功!', 200);
    });
};